<template>
	<div class="account">
		<div style=" width: 100%;display: flex;justify-content: space-between;">
			<div>
				<el-button type="primary" @click="accountDialogShow(null,0)" plain size="mini">
					新增账户
				</el-button>
			</div>
			<!-- 条件查询 -->
			<div style="display: flex;">
				<el-input v-model="selectAccount.accountName" clearable @change="getAccountList"
					style="width: 220px;" placeholder="按开户名,账户搜索" size="mini">
				</el-input>
				<el-date-picker v-model="selectDate" :clearable="false" :type="dateType" 
					placeholder="选择日期" @change="changeDate(0)" style="width: 130px;" size="mini">
				</el-date-picker>
				<el-select v-model="dateType" style="width: 80px;" 
					@change="changeType(0)" size="mini">
					<el-option value="year" label="年"></el-option>
					<el-option value="month" label="月"></el-option>
					<el-option value="date" label="日"></el-option>
				</el-select>
				<el-button @click="reset(0)" size="mini" v-debounce>重置</el-button>
			</div>
		</div>
		<div class="data-table">
			<el-table :data="tableData" v-loading="loading" border stripe 
				style="width: 100%" height="100%">
				<el-table-column prop="i" label="序号" width="50" fixed="left">
				</el-table-column>
				<el-table-column prop="accountName" label="开户名" width="180">
				</el-table-column>
				<el-table-column prop="account" label="账户" width="220">
				</el-table-column>
				<el-table-column prop="balance" label="余额" width="80">
				</el-table-column>
				<el-table-column prop="disburse" :label="disburseLabel()" width="80">
				</el-table-column>
				<el-table-column prop="income" :label="incomeLabel()" width="80">
				</el-table-column>
				<el-table-column prop="accountRemark" label="备注" width="200">
				</el-table-column>
				<el-table-column label="操作" width="150" fixed="right">
					<template slot-scope="scope">
						<el-button v-if="userInfo.roleId === '1'" size="medium" type="text"
							@click="accountDialogShow(scope.row.id,1)">
							编辑
						</el-button>
						<el-divider v-if="userInfo.roleId === '1'" direction="vertical"></el-divider>
						<el-button size="medium" type="text" @click="detailDialogShow(scope.row)">
							明细
						</el-button>
						<el-divider v-if="userInfo.roleId === '1'" direction="vertical"></el-divider>
						<el-button v-if="userInfo.roleId === '1'" size="medium" type="text"
							@click="deleteAccount(scope.row)">
							删除
						</el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
				:current-page="currentPage" :page-sizes="[20, 50, 100]" :page-size="pageSize"
				layout="total, sizes, prev, pager, next, jumper" :total="total">
			</el-pagination>
		</div>
		<!-- 新增/编辑 -->
		<el-dialog :title="title" :visible.sync="accountDialog" width="60%" @close="accountDialogClose">
			<el-form ref="accountForm" :model="selectAccount" :rules="rules" label-width="80px">
				<el-form-item label="开户名" prop="accountName">
					<el-input v-model="selectAccount.accountName"></el-input>
				</el-form-item>
				<el-form-item label="账户" prop="account">
					<el-input v-model="selectAccount.account"></el-input>
				</el-form-item>
				<el-form-item label="余额" prop="balance">
					<el-input v-model="selectAccount.balance" type="number" step="0.01" 
						@input="checkInput" >
					</el-input>
				</el-form-item>
				<el-form-item label="备注" prop="accountRemark">
					<el-input v-model="selectAccount.accountRemark"></el-input>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="accountDialog = false">取 消</el-button>
				<el-button type="primary" @click="addAccount">确 定</el-button>
			</span>
		</el-dialog>
		<!-- 明细 -->
		<el-dialog title="账户明细" :visible.sync="detailDialog" width="80%" @close="detailDialogClose">
			<div style="display: flex; justify-content: space-between;">
				<div>
					<!-- <el-button type="primary">添加账户明细</el-button> -->
				</div>
				<div>
					<el-date-picker v-model="detailSelectDate" :clearable="false" :type="detailDateType" placeholder="选择日期"
						@change="changeDate(1)">
					</el-date-picker>
					<el-select v-model="detailDateType" style="width: 80px;" @change="changeType(1)">
						<el-option value="year" label="年"></el-option>
						<el-option value="month" label="月"></el-option>
						<el-option value="date" label="日"></el-option>
					</el-select>
					<el-button type="primary" @click="exportExcel" style="margin-left: 10px;">
						导出
					</el-button>
				</div>
			</div>
			<div class="data-table detail-list">
				<el-table :data="detailList" v-loading="detailLoading" border stripe style="width: 100%">
					<el-table-column prop="i" label="序号" width="60" fixed="left">
					</el-table-column>
					<el-table-column prop="account" label="账户" width="220">
					</el-table-column>
					<el-table-column prop="tradingObject" label="交易对象" width="200">
					</el-table-column>
					<el-table-column prop="tradeComment" label="交易说明" width="130">
					</el-table-column>
					<el-table-column prop="tradingHours" label="交易时间" width="180">
					</el-table-column>
					<el-table-column prop="amount" label="交易金额" fit>
						<template slot-scope="scope">
							<span v-if="scope.row.detailType === 2" style="color: #67C23A;">
								{{scope.row.amount}}
							</span>
							<span v-else style="color: #F56C6C;">
								{{scope.row.amount}}
							</span>
						</template>
					</el-table-column>
					<el-table-column prop="balance" label="账户余额" fit>
					</el-table-column>
					<el-table-column prop="remark" label="备注" width="200">
					</el-table-column>
					<el-table-column label="操作" width="80">
						<template slot-scope="scope">
							<el-button size="medium" type="text" @click="remarkDialog(scope.row)">
								备注
							</el-button>
						</template>
					</el-table-column>
				</el-table>
				<el-pagination background @size-change="sizeChange" @current-change="currentChange"
					:current-page="detail.currentPage" :page-sizes="[20, 50, 100]" :page-size="detail.pageSize"
					layout="total, sizes, prev, pager, next, jumper" :total="detail.total">
				</el-pagination>
			</div>
			<!-- 备注弹窗 -->
			<el-dialog width="40%" title="备注" :visible.sync="remarkVisible" append-to-body>
				<div>
					<el-form label-width="80px">
						<el-form-item label="备注">
							<el-input v-model="selectDetail.remark" placeholder="请输入内容"></el-input>
						</el-form-item>
					</el-form>
				</div>
				<span slot="footer" class="dialog-footer">
					<el-button @click="remarkVisible = false">取 消</el-button>
					<el-button type="primary" @click="updateDetailRemark">确 定</el-button>
				</span>
			</el-dialog>
			<!-- 新增账户明细 -->
<!-- 			<el-dialog width="50%" title="新增账户明细" :visible.sync="addDtailShow" append-to-body>
				<div>
					<el-form label-width="80px">
						<el-form-item label="备注">
							<el-input v-model="selectDetail.remark" placeholder="请输入内容"></el-input>
						</el-form-item>
					</el-form>
				</div>
				<span slot="footer" class="dialog-footer">
					<el-button @click="remarkVisible = false">取 消</el-button>
					<el-button type="primary" @click="updateDetailRemark">确 定</el-button>
				</span>
			</el-dialog> -->
		</el-dialog>
	</div>
</template>

<script>
	import orderApi from "../../api/order.js";
	import financeApi from "../../api/financeManage.js"
	export default {
		data() {
			return {
				userInfo: {},
				tableData: [],
				loading: false,
				currentPage: 1,
				pageSize: 50,
				total: 0,
				year: null,
				yearMonth: null,
				yearMonthDay: null,
				selectDate: null,
				dateType: "date",
				detailSelectDate: null,
				detailDateType: "month",
				title: "新增账户",
				accountDialog: false,
				selectAccount: {
					id: null,
					accountName: null,
					account: null,
					balance: null,
					accountRemark: null,
				},
				rules: {
					accountName: [{
						required: true,
						message: '请输入开户名',
						trigger: 'blur'
					}],
					account: [{
						required: true,
						message: '请输入账户',
						trigger: 'blur'
					}],
					balance: [{
						required: true,
						message: '请输入金额',
						trigger: 'blur'
					}]
				},
				detail: {
					accountId: null,
					year: null,
					yearMonth: null,
					yearMonthDay: null,
					detailType: null,
					currentPage: 1,
					pageSize: 50,
					total: 0
				},
				detailDialog: false,
				detailLoading: false,
				detailList: [],
				remarkVisible: false,
				selectDetail: {
					id: null,
					remark: null,
				},
				addDetail: {
					accountId: null,
				}
			};
		},
		created() {
			this.userInfo = JSON.parse(localStorage.getItem("userInfo"));
			this.initializeDate();
			this.getAccountList();
		},
		methods: {
			initializeDate() {
				const currentYear = new Date().getFullYear();
				let currentMonth = new Date().getMonth() + 1;
				let currentDay = new Date().getDate()
				currentMonth = currentMonth < 10 ? '0' + currentMonth : currentMonth;
				currentDay = currentDay < 10 ? '0' + currentDay : currentDay;
				this.yearMonthDay = `${currentYear}-${currentMonth}-${currentDay}`
				this.detail.yearMonth = `${currentYear}-${currentMonth}`
				this.selectDate = this.yearMonthDay;
				this.detailSelectDate = this.detail.yearMonth;
			},
			// 获取账号列表
			getAccountList() {
				this.loading = true
				const data = {
					accountName: this.selectAccount.accountName,
					year: this.year,
					yearMonth: this.yearMonth,
					yearMonthDay: this.yearMonthDay,
					currentPage: this.currentPage,
					pageSize: this.pageSize,
				}
				financeApi.getAccountDetailList(data).then(res => {
					if (res.code === 200) {
						this.total = res.data.total
						if (res.data.accountVoList) {
							this.tableData = res.data.accountVoList.map((item, index) => {
								item.i = (this.currentPage - 1) * this.pageSize + index + 1;
								return item;
							})
						}
					}
				}).finally(() => {
					this.loading = false
				})
			},
			// pageSize变化
			handleSizeChange(pageSize) {
				this.pageSize = pageSize
				this.getAccountList()
			},
			// 页码变化
			handleCurrentChange(curPage) {
				this.currentPage = curPage
				this.getAccountList()
			},
			sizeChange(pageSize) {
				this.detail.pageSize = pageSize
				this.getDetailList();
			},
			currentChange(curPage) {
				this.detail.currentPage = curPage
				this.getDetailList();
			},
			// 日期类型改变
			changeType(index) {
				if (index === 0) {
					this.selectDate = new Date();
					this.changeDate(index);
				} else {
					this.detailSelectDate = new Date();
					this.changeDate(index);
				}
			},
			// 日期改变
			changeDate(index) {
				//console.log("选择的日期==>",this.selectDate)
				if (this.selectDate !== null && this.detailSelectDate !== null) {
					let year = null;
					let month = null;
					let day = null;
					if (index === 0) {
						year = this.selectDate.getFullYear();
						month = this.selectDate.getMonth() + 1; // 月份从 0 开始，需要加 1
						day = this.selectDate.getDate();
					} else {
						year = this.detailSelectDate.getFullYear();
						month = this.detailSelectDate.getMonth() + 1; // 月份从 0 开始，需要加 1
						day = this.detailSelectDate.getDate();
					}
					// 格式化月份和日期，确保始终是两位数
					const formattedMonth = month < 10 ? '0' + month : month;
					const formattedDay = day < 10 ? '0' + day : day;
					// 拼接字符串
					const yearMonth = `${year}-${formattedMonth}`;
					const yearMonthDay = `${year}-${formattedMonth}-${formattedDay}`;
					if (index === 0) {
						this.year = null;
						this.yearMonth = null;
						this.yearMonthDay = null;
						if (this.dateType === "year") {
							this.year = year;
						} else if (this.dateType === "month") {
							this.yearMonth = yearMonth;
						} else {
							this.yearMonthDay = yearMonthDay;
						}
						this.onSubmit();
					} else {
						this.detail.year = null;
						this.detail.yearMonth = null;
						this.detail.yearMonthDay = null;
						if (this.detailDateType === "year") {
							this.detail.year = year;
						} else if (this.detailDateType === "month") {
							this.detail.yearMonth = yearMonth;
						} else {
							this.detail.yearMonthDay = yearMonthDay;
						}
						this.onDetailSubmit();
					}
				}
			},
			// 条件查询提交
			onSubmit() {
				this.currentPage = 1
				this.pageSize = 50
				this.getAccountList()
			},
			// 条件查询提交
			onDetailSubmit() {
				this.detail.currentPage = 1
				this.detail.pageSize = 50;
				this.getDetailList();
			},
			// 重置查询条件
			reset(index) {
				if (index === 0) {
					this.resetData();
					this.dateType = "date"
					this.changeType(index);
				} else {
					this.detail = {
						accountId: null,
						year: null,
						yearMonth: null,
						yearMonthDay: null,
						detailType: null,
						currentPage: 1,
						pageSize: 50,
						total: 0
					}
					this.detailDateType = "month";
					this.changeType(index);
				}
			},
			// 重置数据
			resetData() {
				this.selectAccount = {
					id: null,
					accountName: null,
					account: null,
					balance: null,
					accountRemark: null,
				}
			},
			// 打开账户弹窗
			accountDialogShow(id, index) {
				if (index === 0) {
					// 0新增
					this.title = "新增账户"
					this.resetData()
					this.accountDialog = true;
				} else {
					// 1编辑
					this.title = "编辑账户"
					// 获取账户
					const data = {
						id: id
					}
					financeApi.getAccount(data).then(res => {
						if (res.code === 200) {
							this.selectAccount = res.data
							this.accountDialog = true
						} else {
							this.$message.error("获取账户失败")
						}
					}).catch(err => {
						this.$message.error("获取账户失败")
					})
				}
			},
			// 关闭账户弹窗
			accountDialogClose() {
				this.resetData();
				this.$refs.accountForm.resetFields();
			},
			// 检查输入的金额
			checkInput(e) {
				let inputNumber = parseFloat(this.selectAccount.balance);
				if (inputNumber < 0.00) {
					inputNumber = null;
				}
				// 使用正则表达式匹配小数点后两位以内的数字或整数
				let regex = /^\d+(\.\d{1,2})?$/;
				if (!regex.test(inputNumber)) {
					inputNumber = null
				}
				this.selectAccount.balance = inputNumber
			},
			// 添加账户
			addAccount() {
				this.$refs.accountForm.validate((valid) => {
					if (valid) {
						if (this.selectAccount.id === null) {
							financeApi.addAccount(this.selectAccount).then(res => {
								if (res.code === 200) {
									this.$message.success("添加成功！")
                  this.resetData();
									this.accountDialog = false;
                  this.getAccountList();
								}
							})
						} else {
							financeApi.updateAccount(this.selectAccount).then(res => {
								if (res.code === 200) {
									this.$message.success("修改成功！")
                  this.resetData();
									this.accountDialog = false;
									this.getAccountList();
								}
							})
						}

					} else {
						this.$message.error("请将表单填写完整！")
					}
				});
			},
			// 表格头部列显示文字
			disburseLabel() {
				if (this.dateType === "year") {
					return "年支出"
				} else if (this.dateType === "month") {
					return "月支出"
				}
				return "日支出"
			},
			incomeLabel() {
				if (this.dateType === "year") {
					return "年收入"
				} else if (this.dateType === "month") {
					return "月收入"
				}
				return "日收入"
			},
			// 删除账户
			deleteAccount(item) {
				this.$confirm(`确定要删除该账户吗？[${item.account}]`, "提示", {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					const data = {
						id: item.id
					}
					financeApi.deleteAccount(data).then(res => {
						if (res.code === 200) {
							this.$message.success("删除成功");
							this.reset();
						}
					})
				})
			},
			// 打开明细弹窗
			detailDialogShow(item) {
				this.selectAccount = item;
				this.getDetailList();
				this.detailDialog = true;
			},
			// 获取明细列表
			getDetailList() {
				this.detailLoading = true
				this.detail.accountId = this.selectAccount.id;
				financeApi.getDetailList(this.detail).then(res => {
					if (res.code === 200) {
						this.detail.total = res.data.total;
						this.detailList = res.data.detailVoList.map((item, index) => {
							item.i = (this.detail.currentPage - 1) * this.detail.pageSize + index + 1;
							item.account = this.selectAccount.account;
							if (item.detailType === 2){
								item.amount = "+"+item.amount
							}else {
								item.amount = "-"+item.amount
							}
							return item;
						});
					}
				}).finally(() => {
					this.detailLoading = false
				})
			},
			// 关闭明细弹窗
			detailDialogClose() {
				this.detailSelectDate = new Date();
				this.detailDateType = "month";
				this.resetData();
			},
			// 修改备注弹窗
			remarkDialog(item) {
				this.selectDetail = item
				this.remarkVisible = true
			},
			// 修改备注
			updateDetailRemark(){
				const data = {
					id: this.selectDetail.id,
					remark: this.selectDetail.remark
				}
				financeApi.updateDetailRemark(data).then(res =>{
					if (res.code === 200){
						this.$message.success("修改成功");
						this.remarkVisible = false
						this.reset(1);
					}
				})
			},
			//导出Excel
			exportExcel() {
				const data = this.formatData(this.detailList); // 将数据格式化为xlsx可以识别的格式
				const wb = this.$XLSX.utils.book_new();
				const ws = this.$XLSX.utils.json_to_sheet(data);
				// 设置列宽
				const columnWidths = [
					{wch: 5}, // 序号
					{wch: 20}, // 账户
					{wch: 20}, // 交易对象
					{wch: 25}, // 交易说明
					{wch: 20}, // 交易时间
					{wch: 10}, // 交易金额
					{wch: 10}, // 账户余额
					{wch: 25} // 备注
				];
				ws['!cols'] = columnWidths;
				this.$XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
				let fileName = this.selectAccount.account+"账户明细";
				this.$XLSX.writeFile(wb, fileName+".xlsx");
			},
			formatData(data) {
				// 格式化表格数据，将对象数组转换为数组对象
				return data.map((item) => {
					const {
						i,
						account,
						tradingObject,
						tradeComment,
						tradingHours,
						amount,
						balance,
						remark
					} = item;
					return {
						序号: i,
						账户: account,
						交易对象: tradingObject,
						交易说明: tradeComment,
						交易时间: tradingHours,
						交易金额: amount,
						账户余额: balance,
						备注: remark,
					};
				});
			},
		}
	}
</script>

<style>
	.account {
		height: 100%;
	}

	.data-table {
		height: 94%;
		display: flex;
		flex-direction: column;
		align-items: flex-end;
		justify-content: center;
		margin-top: 10px;
	}

	.detail-list {
		height: 500px;
	}
</style>